import {getAction,postAction,httpAction,deleteAction,putAction} from "../http/request";
import {getstateList,getcurlist,getcityList,getBdPortList,getBdFeeTypeList,getallusers,getallsalesmans,getallrealtion,getallcountries,getCasedCountry} from "../api/order";
import el from "element-ui/src/locale/lang/el";

export default {
    data() {
        return {
            queryForm: {},
            filterForm: {},
            tableData: [],
            loading: false,
            form:{},
            ipagination: {
                currentPage: 1,
                pageSize: 10,
                pageSizes: [10, 20, 50, 100],
                total: 0
            },
            isorter: {
                prop: '',
                order: ''
            },
            selectedRowKeys: [],
            selectionRows: [],

            disableMixinMounted: false,

            //业务员数据
            salesmanlist: [],
            //添加人数据
            userlist:[],
            //国家基础数据
            countrylist:[],
            //省基础数据
            statelist:[],
            //市基础数据
            citylist:[],
            //币种基础数据
            curlist:[],
            options:[],
            nameList:[],
            emailList:[],
            //港口基础数据
            bdPortList:[],
            //费用类别基础数据
            feeTypeList:[],
        }
    },
    created: function () {

    },
    mounted() {
        //给queryForm赋值
        if (this.queryForm.initCountry) {
            this.initCountryList();
        }
        if (this.queryForm.initUser) {
            this.initUserList();
        }
        if (this.queryForm.initCur) {
            this.initCurList();
        }
        if (this.queryForm.initSalesman) {
            this.initSalesmanList();
        }
        // this.initCasedCountry();
        if (!this.disableMixinMounted) {
            this.handleQuery()
        }
        if (this.queryForm.initBdPort) {
            this.initBdPortList();
        }
        if (this.queryForm.initFeeType) {
            this.initBdFeeTypeList();
        }
    },
    methods: {
        //初始化业务员
        initSalesmanList(){
            getallsalesmans()
                .then((res)=>{
                    if (res.success){
                        for(var i=0;i<res.result.records.length;i++){
                            var obj = {};
                            obj.value = res.result.records[i].id;
                            obj.label = res.result.records[i].username+"-"+res.result.records[i].realname;
                            this.salesmanlist.push(obj);
                        }


                    }
                })
        },
        //初始化币种
        initCurList(){
            getcurlist().then(res => {
                if (res.success) {
                    for (var i = 0; i < res.result.length; i++) {
                        var obj = {};
                        obj.value = res.result[i].shortName;
                        obj.label = res.result[i].name + "-" + res.result[i].shortName;
                        this.curlist.push(obj);
                    }
                }
            }).catch(err=>{
                this.$message.error(err.message);
            })
        },
        initUserList(){
            getallusers()
                .then((res)=>{
                    if (res.success){
                        for(var i=0;i<res.result.records.length;i++){
                            var obj = {};
                            obj.value = res.result.records[i].id;
                            obj.label = res.result.records[i].username;
                            this.userlist.push(obj);
                        }
                    }
                })
        },
        //初始化港口数据
        initBdPortList(){
            getBdPortList().then(res=>{
                if (res.success){
                    for(var i=0;i<res.result.length;i++){
                        var obj = {};
                        obj.value = res.result[i].cnName;
                        obj.label = res.result[i].cnName;
                        this.bdPortList.push(obj);
                    }
                }
            }).catch(err=>{
                this.$message.error(err)
            })
        },
        //初始化费用类别
        initBdFeeTypeList(){
            getBdFeeTypeList().then(res=>{
                if (res.success){
                    for(var i=0;i<res.result.length;i++){
                        var obj = {};
                        obj.value = res.result[i].chineseName;
                        obj.label = res.result[i].chineseName;
                        this.feeTypeList.push(obj);
                    }
                }
            }).catch(err=>{
                this.$message.error(err)
            })
        },
        //初始化国家级联数据
        initCasedCountry(){
            getCasedCountry().then(res=>{
                this.options = res.result;
                console.log('级联集合',this.options);
            }).catch(err=>{
                this.$message.error(err)
            })
        },
        //初始化国家基础数据
        initCountryList(){
            getallcountries().then(res=>{
                if (res.success){
                    for (var i=0;i<res.result.length;i++){
                        let obj = {};
                        obj.value = res.result[i].cnName;
                        obj.label = res.result[i].twoCode + "-" + res.result[i].cnName;
                        this.countrylist.push(obj);
                    }
                }
            })
        },
        //初始化省数据
        initStateList(val){
            this.statelist=[];
            this.citylist=[];
            if (val){
                getstateList({cnName:val})
                    .then((res)=>{

                        if (res.success){
                            for (var i=0;i<res.result.records.length;i++){
                                let obj = {};
                                obj.value = res.result.records[i].cname;
                                obj.label = res.result.records[i].code + "-" + res.result.records[i].cname;
                                this.statelist.push(obj);
                            }
                        }
                    })
            }else {
               this.form.city = '';
               this.form.state = '';
               this.form.bdState = '';
               this.form.bdCity = '';
            }

        },
        //初始化城市数据
        initCityList(val){
            this.citylist=[];
            if (val){
                getcityList({cname:val})
                    .then((res)=>{
                        if (res.success){
                            for (var i=0;i<res.result.records.length;i++){
                                let obj = {};
                                obj.value = res.result.records[i].id;
                                obj.label = res.result.records[i].code + "-" + res.result.records[i].cname;
                                this.citylist.push(obj);
                            }
                        }
                    })
            }else {

            }

        },
        handleSizeChange(val) {
            this.ipagination.currentPage = 1
            this.ipagination.pageSize = val
            this.handleQuery()
        },
        handleCurrentChange(val) {
            this.ipagination.currentPage = val
            this.handleQuery()
        },
        handleReset(){
            this.queryForm = {}
            this.ipagination.currentPage = 1
            this.handleQuery()
        },
        handleResetFilter() { // 清空表格过滤器
            this.$refs.GTable.handlePureClear()
            this.filterForm = {}
        },
        handleResetAll(){
            this.handleResetFilter()
            this.handleReset()
        },
        handleSearch() {
            this.ipagination.currentPage = 1
            this.handleQuery()
        },
        handleQuery(){
            this.loading = true
            let form = { ...this.queryForm, ...this.filterForm }
            for(let item in form) {
                if(typeof form[item] === 'string') {
                    form[item] = form[item].trim()
                    if (form[item] === ''){
                        form[item] = null
                    }
                }
            }
            const { prop, order } = this.isorter
            const params = {
                ...form,
                column: prop,
                order: order.indexOf('desc') !== -1 ? 'desc' : 'asc',
            }

            if(this.ipagination) {
                params.pageNo = this.ipagination.currentPage
                params.pageSize = this.ipagination.pageSize
            }
            console.log("查询对象",params)
            getAction(this.url.list, params).then((res)=>{
                if(res.success) {
                    const { records, total } = res.result
                    this.tableData = records || res.result;
                    console.log("表单数据",this.tableData);
                    this.ipagination && (this.ipagination.total = total || res.result.length)
                }
            }).finally(() => {
                this.loading = false
            })
        },
        handleTableChange({ prop, order }) {
            if(order === null) {
                 // this.handleResetSorter()
            } else {
                this.$set(this.isorter, 'prop', prop)
                this.$set(this.isorter, 'order', order)
            }
            this.handleSearch()
        },
        handleResetSorter() {
            this.$set(this.isorter, 'prop', 'createTime')
            this.$set(this.isorter, 'order', 'descending')
        },
        handleTableQueryChange(form, flag, clearSorter = false) {
            this.filterForm = { ...form }
            clearSorter && this.handleResetSorter()
            flag && this.handleQuery()
        },
        handleClearSelection() {
            this.selectionRows = []
            this.selectedRowKeys = []
            this.$refs.GTable.handleClearSelection()
        },
        handleSelectionChange(selection) { // 多选
            let arr = []
            this.nameList = []
            this.emailList = []
            for(let i = 0; i < selection.length; i++) {
                arr.push(selection[i]['id'])
                this.nameList.push(selection[i]['name'])
                this.emailList.push(selection[i]['email'])
            }
            this.selectionRows = selection
            this.selectedRowKeys = [...arr]
            console.log('选择的ids',this.selectedRowKeys.join(','));
        },
        handleTableCurrentChange(currentRow) { // 单选
            this.selectionRows = [currentRow]
            this.selectedRowKeys = [currentRow['id']]
        },
        handleExportXls(fileName) {
            if (!fileName || typeof fileName != 'string') {
                fileName = '导出文件'
            }

            let params = { ...this.queryForm, ...this.filterForm }
            if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
                params['selections'] = this.selectedRowKeys.join(',')
                console.log('选择的ids',this.selectedRowKeys.join(','));
                params['ids'] = this.selectedRowKeys.join(',')
            }else{
                params['ids'] = '';
            }

            postAction(this.url.exportXlsUrl, params, { responseType: 'blob' }).then((data) => {
                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
                } else {
                    let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
                    let link = document.createElement('a')
                    link.style.display = 'none'
                    link.href = url
                    link.setAttribute('download', fileName + '.xls')
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link) //下载完成移除元素
                    window.URL.revokeObjectURL(url) //释放掉blob对象
                }
            })
        },
        //下载产品导入模板
        downloadModel(){
            let url = this.url.downloadModel;
            let params = { ...this.queryForm, ...this.filterForm }
            let fileName = "数据模板_产品导入";
            postAction(url,params,{responseType : 'blob'})
                .then(response=>{
                    if (!response) {
                        return
                    }
                    const blob = new Blob([response])
                    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                        navigator.msSaveBlob(blob,fileName )
                    } else {
                        let u = window.URL.createObjectURL(response)
                        let aLink = document.createElement('a')
                        aLink.style.display = 'none'
                        aLink.href = u
                        aLink.setAttribute('download', fileName + '.xlsx')
                        document.body.appendChild(aLink)
                        aLink.click()
                        document.body.removeChild(aLink)
                        window.URL.revokeObjectURL(u)
                    }
                }).catch(err=>{
                this.$message.error(err.message);
            })
        },
    },
}
